﻿using System;
using System.Data;
using System.Data.SqlClient;

namespace LsoaClass.SystemMaintain
{
    public class BranchDeptClass : LsDBClass
    {
        /// <summary>
        /// 获取机构部门信息列表。
        /// </summary>
        /// <param name="parentNo">父编号</param>
        /// <param name="onlylBranch">只取机构信息</param>
        /// <param name="ds">返回数据集</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string list(int parentNo, bool onlylBranch, out DataSet ds)
        {
            ds = null;
            DBClass dbc = new DBClass();
            try
            {
                SqlCommand cmd = dbc.getSqlCommand(@"
                    declare @OrderNo varchar(50)
                    if @ParentNo = 0
                    begin
	                    if @OnlyBranch = 1
		                    select No, Name, IsDept, ParentNo, OrderNo from BranchDept_T where IsDept = 0 and IsDel = 0 order by OrderNo
	                    else
		                    select No, Name, IsDept, ParentNo, OrderNo from BranchDept_T where IsDel = 0 order by OrderNo
                    end else
                    begin
	                    select @OrderNo = OrderNo from BranchDept_T where No = @ParentNo
	                    if @OnlyBranch = 1
		                    select No, Name, IsDept, ParentNo, OrderNo from BranchDept_T where left(OrderNo, len(@OrderNo)) = @OrderNo and IsDept = 0 and IsDel = 0 order by OrderNo
	                    else
		                    select No, Name, IsDept, ParentNo, OrderNo from BranchDept_T where left(OrderNo, len(@OrderNo)) = @OrderNo and IsDel = 0 order by OrderNo
                    end");
                cmd.Parameters.AddWithValue("@ParentNo", parentNo);
                cmd.Parameters.AddWithValue("@OnlyBranch", onlylBranch);
                ds = dbc.getDataSetBySqlCommand(cmd);
                funResult.Code = 0;
                funResult.Msg = "获取机构部门信息列表成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "获取机构部门信息列表失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 获取下级机构部门信息列表。
        /// </summary>
        /// <param name="parentNo">父编号</param>
        /// <param name="onlylBranch">只取机构信息</param>
        /// <param name="ds">返回数据集</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string childList(int parentNo, bool onlylBranch, out DataSet ds)
        {
            ds = null;
            DBClass dbc = new DBClass();
            try
            {
                SqlCommand cmd = dbc.getSqlCommand(@"
                    if @OnlyBranch = 1
	                    select No, Name, IsDept, ParentNo, OrderNo from BranchDept_T where ParentNo = @ParentNo and IsDept = 0 and IsDel = 0 order by OrderNo
                    else
	                    select No, Name, IsDept, ParentNo, OrderNo from BranchDept_T where ParentNo = @ParentNo and IsDel = 0 order by OrderNo");
                cmd.Parameters.AddWithValue("@ParentNo", parentNo);
                cmd.Parameters.AddWithValue("@OnlyBranch", onlylBranch);
                ds = dbc.getDataSetBySqlCommand(cmd);
                funResult.Code = 0;
                funResult.Msg = "获取机构部门信息列表成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "获取机构部门信息列表失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }        

        /// <summary>
        /// 获取机构部门信息
        /// </summary>
        /// <param name="no">机构部门编号</param>
        /// <param name="ds">返回数据集</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string getInfo(int no, out DataSet ds)
        {
            ds = null;
            DBClass dbc = new DBClass();
            try
            {
                ds = dbc.getDataSetBySql("select * from BranchDept_T where No = " + no.ToString());
                funResult.Code = 0;
                funResult.Msg = "获取机构部门信息成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "获取机构部门信息失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }        

        /// <summary>
        /// 增加机构部门信息
        /// </summary>
        /// <param name="operatorID">操作员帐号</param>
        /// <param name="name">机构部门名称</param>
        /// <param name="isDept">0表示机构，1表示部门</param>
        /// <param name="parentNo">父编号</param>
        /// <param name="bak">备注说明</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string add(string operatorID, string name, bool isDept, int parentNo, string bak)
        { 
            DBClass dbc = new DBClass();
            try
            {
                SqlCommand cmd = dbc.getSqlCommand(@"
                    declare @OrderNo varchar(50), @ParentOrderNo varchar(50)
                    select @ParentOrderNo = OrderNo from BranchDept_T where No = @ParentNo
                    select @OrderNo = max(right(OrderNo, 5)) from BranchDept_T where ParentNo = @ParentNo
                    if @OrderNo is null
	                    set @OrderNo = 10000
                    else 
	                    set @OrderNo = @OrderNo + 1
                    set @OrderNo = @ParentOrderNo + @OrderNo 
                    insert into BranchDept_T(Name, IsDept, ParentNo, OrderNo, Bak, Creater)
	                    values (@Name, @IsDept, @ParentNo, @OrderNo, @Bak, @Creater)
                    select @@Identity");
                cmd.Parameters.AddWithValue("@Name", name);
                cmd.Parameters.AddWithValue("@IsDept", isDept);
                cmd.Parameters.AddWithValue("@ParentNo", parentNo);
                cmd.Parameters.AddWithValue("@Bak", bak);
                cmd.Parameters.AddWithValue("@Creater", operatorID);
                string no = Convert.ToString(cmd.ExecuteScalar());
                SystemClass.recordLog(operatorID, "增加机构部门信息。（编号：" + no + "，名称：" + name + "）");
                funResult.Code = 0;
                funResult.Msg = "增加机构部门信息成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "增加机构部门信息失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 修改机构部门信息
        /// </summary>
        /// <param name="operatorID">操作员帐号</param>
        /// <param name="no">机构部门编号</param>
        /// <param name="name">机构部门名称</param>
         /// <param name="bak">备注说明</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string modify(string operatorID, int no, string name, string bak)
        {
            DBClass dbc = new DBClass();
            try
            {
                SqlCommand cmd = dbc.getSqlCommand("update BranchDept_T set Name = @Name, Bak = @Bak where No = @No");
                cmd.Parameters.AddWithValue("@Name", name);
                cmd.Parameters.AddWithValue("@Bak", bak);
                cmd.Parameters.AddWithValue("@No", no);
                cmd.ExecuteNonQuery();
                SystemClass.recordLog(operatorID, "修改机构部门信息。（编号：" + no + "，名称：" + name + "）");
                funResult.Code = 0;
                funResult.Msg = "修改机构部门信息成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "修改机构部门信息失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 删除机构部门信息
        /// </summary>
        /// <param name="operatorID">操作员帐号</param>
        /// <param name="no">机构部门编号</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string delete(string operatorID, int no)
        { 
            DBClass dbc = new DBClass();
            try
            {
                SqlCommand cmd = dbc.getSqlCommand(@"
                    declare @RetStr nvarchar(50), @Log nvarchar(50)
                    if exists (select * from BranchDept_T where ParentNo = @No and IsDel = 0)
	                    set @RetStr = '15120000|其下有机构或部门。'
                    else if exists (select * from User_T where BranchNo = @No and UserState <> 1)
	                    set @RetStr = '15120001|该机构下有用户。' 
                    else if exists (select * from User_T where DeptNo = @No and UserState <> 1)
	                    set @RetStr = '15120002|该部门下有用户。'
                    else 
                    begin
	                    update BranchDept_T set IsDel = 1 where No = @No
	                    set @Log = '删除机构部门信息。（编号：' + convert(nvarchar(50), @No) + '）' 
	                    exec RecordLog @OperatorID, @Log
	                    set @RetStr = '0|删除机构部门信息成功。'
                    end
                    select @RetStr");
                cmd.Parameters.AddWithValue("@No", no);
                cmd.Parameters.AddWithValue("@OperatorID", operatorID);
                funResult.RetStr = Convert.ToString(cmd.ExecuteScalar());
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "删除机构部门信息失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }

        /// <summary>
        /// 调整机构部门顺序
        /// </summary>
        /// <param name="operatorID">操作员帐号</param>
        /// <param name="noStr">机构部门编号串（调整后的顺序）</param>
        /// <returns>返回代码和提示信息组合成的字符串</returns>
        public static string adjustSequence(string operatorID, string noStr)
        {
            DBClass dbc = new DBClass();
            try
            {
                SqlCommand cmd = dbc.getSqlCommand(@"
                    declare @NoStr varchar(max) 
                    declare @Pos int, @I int
                    declare @No int, @OrderNo varchar(50), @NewOrderNo varchar(50)
                    set @NoStr = @NoStrValue + ','
                    set @I = 10000
                    while charindex(',', @NoStr) > 0
                    begin
	                    set @Pos = charindex(',', @NoStr)
	                    set @No = convert(int, substring(@NoStr, 1, @Pos - 1))
	                    select @OrderNo = OrderNo from BranchDept_T where No = @No
	                    set @NewOrderNo = left(@OrderNo, len(@OrderNo) - 5) + convert(varchar(50), @I)
	                    update BranchDept_T set OrderNo = 'T' + @NewOrderNo + right(OrderNo, len(OrderNo) - len(@NewOrderNo)) where left(OrderNo, len(@OrderNo)) = @OrderNo  --调整机构部门包括下级机构部门顺序号
	                    update User_T set OrderNo = 'T' + @NewOrderNo + right(OrderNo, len(OrderNo) - len(@NewOrderNo)) where left(OrderNo, len(@OrderNo)) = @OrderNo  --调整用户顺序号 
	                    set @I = @I + 1
	                    set @NoStr = substring(@NoStr, @Pos + 1, len(@NoStr) - @Pos)
                    end
                    update BranchDept_T set OrderNo = Replace(OrderNo, 'T', '')
                    update User_T set OrderNo = Replace(OrderNo, 'T', '')");
                cmd.Parameters.AddWithValue("@NoStrValue", noStr);
                cmd.ExecuteNonQuery();
                SystemClass.recordLog(operatorID, "调整机构部门顺序。（编号：" + noStr + "）");
                funResult.Code = 0;
                funResult.Msg = "调整机构部门顺序成功。";
            }
            catch (Exception ex)
            {
                funResult.Code = 13120000;
                funResult.Msg = "调整机构部门顺序失败。" + ex.Message;
            }
            finally
            {
                dbc.close();
            }
            return funResult.RetStr;
        }
    }
}
